package com.yidu.web.listener;

import com.yidu.web.dao.WsJokeDao;
import com.yidu.web.model.WsJoke;
import com.yidu.web.utils.HTMLTools;
import com.yidu.web.utils.SpiderTools;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * ServletContext监听器
 */
public class SpiListener implements ServletContextListener {

    public static Map<String, WsJoke> map = null ;

    WsJokeDao wsJokeDao = new WsJokeDao();

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //初始化时执行
        System.out.println("tomcat已经启动");
        new MyThread().start(); //爬笑话

        //爬笑话的同时,也在爬天气
        //多线程解决
        Thread weatherThread = new Thread(new WeatherThread());
        weatherThread.start();


    }

    /**
     * 笑话的线程
     */
    class MyThread extends Thread{
        @Override
        public void run() {
            while (true){
                map = wsJokeDao.findFlag();
                try {
                    List<WsJoke> list = HTMLTools.jokeTitle(HTMLTools.URL);
                    for(WsJoke joke:list){
                        if(map.get(joke.getFlag())==null) {
                            wsJokeDao.insert(joke);
                        }
                    }

                    Thread.sleep(1000*60*60);

                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 天气线程
     */
    class WeatherThread implements Runnable{

        @Override
        public void run() {
            while (true){
                SpiderTools.getProvince(SpiderTools.urlPro);
                try {
                    Thread.sleep(1000*60*60*24);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //销毁时执行
    }
}
